import pytest, requests, os
from xToolkit import xfile
import jsonpath
from commons.global_var import global_var
from string import Template

# 文档读取
list = xfile.read('接口测试用例.xls').excel_to_dict(sheet=1)


class TestCase:

    @pytest.mark.parametrize("data_info", list)
    def test_run(self, data_info):
        # 接口关联
        url = data_info['接口URL']
        if '$' in url:
            data1 = global_var().show_global()
            print(f"我想看看{data1}")
            url = Template(url).substitute(data1)
        res = requests.request(
            url=url,
            method=data_info['请求方式'],
            params=eval(data_info['URL参数'])
        )
        # cookie = res.cookies.get('JSESSIONID') 提取cookie
        assert res.status_code == data_info['预期状态码'], '状态码不一致！！！'
        # 接口关联
        if data_info['接口关联'] != '':
            response_json = res.json()
            print(f"JSON 响应数据: {response_json}")
            # json提取
            dataList = jsonpath.jsonpath(response_json, '$..' + data_info['接口关联'])  # $.. 匹配所有
            print(dataList[0])
            gv = global_var()
            gv.set_global(data_info['接口关联'], dataList[0])
            print(gv.show_global())

    if __name__ == '__main__':
        pytest.main(['-s',  # 打印
                     '-v',  # 打印日志
                     '--capture=sys',  # 保留系统输出
                     'Test001.py',
                     '--clean-alluredir', '--alluredir=allure-results'])  # 存放测试结果
        os.system(r"allure generate -c -o 蜗牛测试报告")  # 生成html测试报告
        # 命令执行 python .\Test001.py
